/*
	App JS
	Developer:
		Luis Matute 		- luis.matute@me.com
	Description:
		This is the server configuration.
*/

var express = require('express'),
	bodyParser = require('body-parser'),
    exec = require("child_process").exec,
	http = require('http'),
	app = express();

//自定义参数

var password = '123'; //提交密码
var releasewords = 'release'; //发布关建字

//日志
fs = require('fs'),
    accessLogfile = fs.createWriteStream('./access.log', {flags: 'a'}), //访问日志


// all environments
app.set('port', process.env.PORT || 8080);

app.use(bodyParser.urlencoded({
	extended: true
}));

app.get('/', function (req, res, next) {
	res.send('Hello World!')
})


app.post('/deploy/', function (req, res) {
	var hook = JSON.parse(req.body.hook);
    var now = new Date();
    var time = now.getFullYear() + '-' + now.getMonth() + '-' + now.getDate() + ' '
        + now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds();

	if(hook.password != password){
		res.json(200, {message: 'password fail'});
	}else{
        var lastcommit = hook.push_data.commits[hook.push_data.commits.length -1];
        console.log(lastcommit ,lastcommit.message.indexOf(releasewords));
        if(lastcommit.message.indexOf(releasewords) >= 0)//这里意为：如果最后的commit包含"release"则进行自动发布。
        {
            exec('sh ./deploy.sh ' + req.query.p,function(error, stdout, stderr){console.log(error, stdout, stderr);});
            accessLogfile.write('release for Projecp' + req.query.p + time +  ' ' + lastcommit.message+  ' ' + lastcommit.author.name + '\n');
            res.json(200, {message: 'Git Hook received!'});
        }else{
            accessLogfile.write('Skip release ' + time +  ' ' + lastcommit.message+  ' ' + lastcommit.author.name + '\n');
            res.json(200, {message: 'Skip release'});
        }
	}
});

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});
